import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.dart';

extension globalKey on GlobalKey {
  Future<Uint8List?> screenShot({double pixelRatio = 0}) async {
    if (null != currentContext) {
      try {
        RenderObject? boundary = currentContext?.findRenderObject();
        if (0 == pixelRatio) {
          pixelRatio = window.devicePixelRatio;
        }
        if (boundary is RenderRepaintBoundary) {
          var image = await boundary.toImage(pixelRatio: pixelRatio);
          ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
          if (null != byteData) {
            Uint8List pngBytes = byteData.buffer.asUint8List();
            return pngBytes;
          }
        }
      } catch (e) {
        //
      }
    }
    return null;
  }
}
